//
//  MainViewController.m
//  GetPowerDBO
//
//  Created by 周博 on 2017/6/13.
//  Copyright © 2017年 BogoZhou. All rights reserved.
//

#import "MainViewController.h"
#import "BGCollectionView.h"
#import "AddShopViewController.h"
#import "NewAddShopViewController.h"
#import "ShopViewController.h"
#import <SystemConfiguration/CaptiveNetwork.h>
#import "HasInstalledPowerViewController.h"
#import "WaitingRepairViewController.h"
#import "WaitingRepairViewController2.h"
#import "ChooseSubUserViewController.h"

@interface MainViewController ()
{
    BOOL _isShow;
}
@property (nonatomic,strong) BGCollectionView *collectionView;

@property (nonatomic,strong) NSMutableArray *itemsArray;

@end

@implementation MainViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    [self loadMainListData];
//    [self UISetting];

    [self firstRightSetting];
    

}

- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    [self loadMainMessage];
//    [self getWiFiNameFun];
}

- (void)UISetting{
    
    if ([BGFunctionHelper isNULLOfString:kUserAdmin]) {
        [[NSNotificationCenter defaultCenter]postNotificationName:@"sign" object:nil];
        return;
    }
    if ([BGFunctionHelper isNULLOfString:kOrganization_id]) {
        [[NSNotificationCenter defaultCenter]postNotificationName:@"sign" object:nil];
        return;
    }
    
    if ([kOrganization_id isEqualToString:@"1"] || [kUserAdmin isEqualToString:@"1"]) {
        _buttonTop.hidden = NO;
        
        if ([kUserId isEqualToString:kAdminUserId]) {
            _labelName.text = kUserName;
            _labelMobile.text = kMobile;
            _labelAddress.text = @"";
        }else{
            _labelName.text = [NSString stringWithFormat:@"%@(%@)",kUserName,kSubUserName];
            _labelMobile.text = [NSString stringWithFormat:@"%@(%@)",kMobile,kSubMobile];
            _labelAddress.text = [NSString stringWithFormat:@"%@",kCityName];
        }
        
    }else{
        _buttonTop.hidden= YES;
        _labelName.text = kUserName;
        _labelMobile.text = kMobile;
        _labelAddress.text = @"";
    }
    
    
    if (_collectionView) {
        _reloadButton.hidden = YES;
    }else{
        _reloadButton.hidden = NO;
    }
}

- (void)loadMainMessage{
//    NSLog(@"访问");
//    [self.hub hideAnimated:YES];
//    
//    self.hub = [MBProgressHUD showHUDAddedTo:self.view animated:YES];
//    
//    // Set the label text.
//    self.hub.label.text = NSLocalizedString(@"加载中...", @"HUD loading title");
    [[AFClient shareInstance] getMainMessageByUserId:kUserId ProgressBlock:nil success:^(id responseBody) {
        [self.hub hideAnimated:YES];
        if ([responseBody[@"code"] integerValue] == 200) {
            /*
             "online_num": "122",   //WiFi在线
             "offline_num": "268",  //WiFi离线
             "mima_num": "0"       //密码设备
             */
            NSDictionary *dic = responseBody[@"data"];
            _labelLine2_1.text = [NSString stringWithFormat:@"%ld",[dic[@"already_anzhuang"] integerValue]];
            _labelLine2_2.text = [NSString stringWithFormat:@"%ld",[dic[@"online_num"] integerValue]];
            _labelLine2_3.text = [NSString stringWithFormat:@"%ld",[dic[@"offline_num"] integerValue]];
            _labelLine2_4.text = [NSString stringWithFormat:@"%ld",[dic[@"mima_num"] integerValue]];
            _labelLine2_5.text = [NSString stringWithFormat:@"%ld",[dic [@"already_withdrawn"] integerValue]];
            _labelLine2_6.text = [NSString stringWithFormat:@"%ld",[dic [@"already_fault"] integerValue]];

            _labelFirst.text = [NSString stringWithFormat:@"%ld",[dic[@"already_pushe"] integerValue]];
            _labelSecond.text = [NSString stringWithFormat:@"%ld",[dic[@"stay_pushe"] integerValue]];
            _labelThird.text = [NSString stringWithFormat:@"%ld",[dic[@"maintenance_num"] integerValue]];
            
            NSString *adminString = kAdmin;
            if ([BGFunctionHelper isNULLOfString:kAdmin]) {
                [[NSNotificationCenter defaultCenter] postNotificationName:@"sign" object:nil];
                return ;
            }
            if (adminString.integerValue == 0) {
                _layoutLine2Height.constant = 50;
            }else{
                _layoutLine2Height.constant = 100;
            }
            [self updateFocusIfNeeded];
            [self creatCollectionView];

            [self newVersonFunc];
        }else{
            kAlert(responseBody[@"message"]);
        }
    } failure:^(NSError *error) {
        [self.hub hideAnimated:YES];
    }];
}

- (void)loadMainListData{
//    [self.hub hideAnimated:YES];
//    
//    self.hub = [MBProgressHUD showHUDAddedTo:self.view animated:YES];
//    
//    // Set the label text.
//    self.hub.label.text = NSLocalizedString(@"加载中...", @"HUD loading title");
    _itemsArray = [NSMutableArray array];

    [[AFClient shareInstance] getMenuByEid:kUserId progressBlock:nil success:^(id responseBody) {
        if ([responseBody[@"code"] integerValue] == 200) {
            for (NSDictionary *dic in responseBody[@"data"]) {
                MainListModel *listModel = [[MainListModel alloc] init];
                [listModel setValuesForKeysWithDictionary:dic];
                [_itemsArray addObject:listModel];
            }
            [self creatCollectionView];
        }else{
            kAlert(responseBody[@"message"]);
        }
        [self.hub hideAnimated:YES];
    } failure:^(NSError *error) {
        [self.hub hideAnimated:YES];
    }];
}

- (void)newVersonFunc{
//    NSLog(@"访问最新版本");
    [[AFClient shareInstance] getNewVersonProgressBlock:nil success:^(id responseBody) {
//        NSLog(@"访问最新版本");
        if ([responseBody[@"code"] integerValue] == 200) {
            NSDictionary *dict = responseBody[@"data"];
            NewVersonModel *model = [[NewVersonModel alloc] init];
            [model setValuesForKeysWithDictionary:dict];
            
            if (model.show_status.integerValue > 0) {
                [self checkVerson:model];
            }
        }
        [self UISetting];
    } failure:^(NSError *error) {
    }];
}

- (void)creatCollectionView{
    
    [_collectionView removeFromSuperview];
    _collectionView = nil;
    
//    if (!_collectionView) {
    NSString *adminString = kAdmin;
    CGFloat height;
    if (adminString.integerValue == 0) {
        height = kScreenSize.height - 259;
    }else{
        height = kScreenSize.height - 309;
    }
        _collectionView = [[BGCollectionView alloc] initWithFrame:CGRectMake(0, 0, _viewCollec.sizeWidth, height)withDataArray:_itemsArray];
        [_viewCollec addSubview:_collectionView];
//        _collectionView.collectionView.mj_header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
//            [self loadMainListData];
//            [_collectionView.collectionView.mj_header endRefreshing];
//        }];

//    }
    

    [_collectionView reloadDataByArray:_itemsArray];

    _reloadButton.hidden = YES;
}
#pragma mark - 点击事件
//已铺设11； 待铺设12
- (IBAction)pusheButtonClick:(UIButton *)sender {
    UIStoryboard *storyboard = kMainStroyboard;
    ShopViewController *shopVC = [storyboard instantiateViewControllerWithIdentifier:@"ShopViewController"];
    if (sender.tag == 11) {
        shopVC.typeValue = @"0";
    }else {
        shopVC.typeValue = @"1";
    }
    [self.navigationController pushViewController:shopVC animated:YES];
}

//点击右上角退出
- (IBAction)quitButtonClick:(UIButton *)sender {
    
    UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"提示" message:@"你是否铁了心要退出？" preferredStyle:UIAlertControllerStyleAlert];
    
    UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
        
    }];
    
    UIAlertAction *sureAction = [UIAlertAction actionWithTitle:@"是的" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        [[NSUserDefaults standardUserDefaults] removeObjectForKey:@"mobile"];
        [[NSUserDefaults standardUserDefaults] removeObjectForKey:@"userName"];
        [[NSUserDefaults standardUserDefaults] removeObjectForKey:@"SubMobile"];
        [[NSUserDefaults standardUserDefaults] removeObjectForKey:@"SubUserName"];
        [[NSUserDefaults standardUserDefaults] removeObjectForKey:@"userId"];
        [[NSUserDefaults standardUserDefaults] removeObjectForKey:@"adminUserId"];
        [[NSUserDefaults standardUserDefaults] removeObjectForKey:@"created"];
        [[NSUserDefaults standardUserDefaults] removeObjectForKey:@"cityName"];
        [[NSUserDefaults standardUserDefaults] removeObjectForKey:@"organization_id"];
        [[NSUserDefaults standardUserDefaults]removeObjectForKey:@"admin"];
        
        [[NSNotificationCenter defaultCenter] postNotificationName:@"sign" object:nil];
    }];
    
    [alert addAction:cancelAction];
    [alert addAction:sureAction];
    [self presentViewController:alert animated:YES completion:nil];
}

#pragma mark - 右下角充点电方法实现

- (void)firstRightSetting{
    _imageViewChongDD.frame = CGRectMake(45, 0, 60, 60);
    _imageViewChongDD.image = [UIImage imageNamed:@"chongdiandian"];
    _buttonLeft.hidden = YES;
    _isShow = YES;
}

- (IBAction)topButtonClick:(UIButton *)sender {
    UIStoryboard *storyboard = kMainStroyboard;
    ChooseSubUserViewController *chooseSubVC = [storyboard instantiateViewControllerWithIdentifier:@"ChooseSubUserViewController"];
    [self.navigationController pushViewController:chooseSubVC animated:YES];
}


//重新加载按钮
- (IBAction)reloadButtonClick:(UIButton *)sender {
    [self loadMainListData];
}

//点击已安装 890 - 893
/*
 if (_defaultValueNUM.integerValue == 0) {
 _defaultValueNUM = [NSNumber numberWithInteger:1];
 }
 if (_zaixianNUM.integerValue == 0) {
 _zaixianNUM = [NSNumber numberWithBool:0];
 }
 if (_dianliangNUM.integerValue == 0) {
 _dianliangNUM = [NSNumber numberWithBool:0];
 }
 if (_antianNUM.integerValue == 0) {
 _antianNUM = [NSNumber numberWithBool:0];
 }
 if (_leixingNUM.integerValue == 0) {
 _leixingNUM = [NSNumber numberWithBool:0];
 }
 */
- (IBAction)hasInstalledButtonClick:(UIButton *)sender {
    UIStoryboard *storyboard = kMainStroyboard;
    HasInstalledPowerViewController *hasInstalledVC = [storyboard instantiateViewControllerWithIdentifier:@"HasInstalledPowerViewController"];
    if (sender.tag == 890) {
        hasInstalledVC.defaultValueNUM = [NSNumber numberWithBool:0];
    }else if(sender.tag == 891){//wifi在线
        hasInstalledVC.defaultValueNUM = [NSNumber numberWithInteger:2];

        hasInstalledVC.zaixianNUM = [NSNumber numberWithInteger:102];
        hasInstalledVC.leixingNUM = [NSNumber numberWithInteger:501];
    }else if (sender.tag == 892){//WiFi离线
        hasInstalledVC.defaultValueNUM = [NSNumber numberWithInteger:2];

        hasInstalledVC.zaixianNUM = [NSNumber numberWithInteger:101];
        hasInstalledVC.leixingNUM = [NSNumber numberWithInteger:501];
    }else{//密码设备
        hasInstalledVC.defaultValueNUM = [NSNumber numberWithInteger:2];

        hasInstalledVC.leixingNUM = [NSNumber numberWithInteger:502];
    }
    
    [self.navigationController pushViewController:hasInstalledVC animated:YES];
}

//待维护
- (IBAction)waitingRepairButtonClick:(UIButton *)sender {
    UIStoryboard *storyboard = kMainStroyboard;
    WaitingRepairViewController2 *waitingRepairVC = [storyboard instantiateViewControllerWithIdentifier:@"WaitingRepairViewController2"];
    [self.navigationController pushViewController:waitingRepairVC animated:YES];
}



/**
 充点电左边按钮

 */
- (IBAction)leftButtonClick:(UIButton *)sender {
//    kAlert(@"点击添加商户");
    UIStoryboard *storyboard = kMainStroyboard;
    NewAddShopViewController *addShopVC = [storyboard instantiateViewControllerWithIdentifier:@"NewAddShopViewController"];
    addShopVC.jumpType = @"2";
    [self.navigationController pushViewController:addShopVC animated:YES];
}


/**
 充点电右边按钮

 */
- (IBAction)rightButtonClick:(UIButton *)sender {
    [self deepViewFun:_isShow];
    _isShow = !_isShow;
}

- (void)deepViewFun:(BOOL)show{
        if (show) {
            [UIView animateWithDuration:0.4 animations:^{
                _imageViewChongDD.frame = CGRectMake(0, 0, 105, 60);
                _buttonLeft.hidden = NO;
            } completion:^(BOOL finished) {
                _imageViewChongDD.image = [UIImage imageNamed:@"chongdiandian01"];
            }];
        }else{
            [UIView animateWithDuration:0.5 animations:^{
                _imageViewChongDD.frame = CGRectMake(45, 0, 60, 60);
                _imageViewChongDD.image = [UIImage imageNamed:@"chongdiandian"];
                _buttonLeft.hidden = YES;
            }];
        }
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
